package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.IUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * @ClassName: IUserLoginServiceImpl
 * @Auther: syq
 * @Date: 2021/7/14 10:35
 * @Version 1.0
 */
@Service
public class IUserLoginServiceImpl implements IUserLoginService {
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public Map<String, String> login(String grant_type, String username, String password, String cilenid, String secret) {
        String url = "http://localhost:9001/oauth/token";
        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
        body.add("grant_type",grant_type);
        body.add("username",username);
        body.add("password",password);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        String authorization ="Basic "+ Base64.getEncoder().encodeToString(new String(cilenid + ":" + secret).getBytes());
        headers.add("Authorization",authorization);
        HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(body,headers);
        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        return exchange.getBody();
    }

}
